$(function() {
	/*===图片懒加载===*/
	start();
	$(window).on('scroll', function() {
		start();
	});
	/*===图片轮播===================================================*/
	var PhotosSwi = new Swiper('.PhotosSwi .swiper-container', {
		pagination: '.PhotosSwi .swiper-pagination',
		paginationClickable: '.PhotosSwi .swiper-pagination',
		effect: 'effect'
	});
	/*===tab切换===================================================*/
	$(".homeMo10 .tabBars .tabBar").eq(0).addClass("active");
	$(".homeMo10 .tabCons .tabCon").eq(0).addClass("active");
	tabChange(".homeMo13 .tabBars .tabBar", ".homeMo13 .tabCons .tabCon", "active");
	/*===文字输入数量限制=========*/
	$(".textCount").keyup(function() {
		var len = $(this).val().length;
		var maxLen = $(this).attr("data-count");
		var count = $(this).next(".count").find(".textLen");
		if (len > (maxLen-1)) {
			$(this).val($(this).val().substring(0, maxLen));
			count.text(maxLen);
		}
		if (len > maxLen) {
			count.text(maxLen);
		} else {
			count.text(len);
		}
	});
	/*===申请表单提交===============*/
	$("#applyFormSub").click(function() {
		var address = $("#address").text();
		var name = $("#name").val();
		var age = $("#age").val();
		var hangye = $("#hangye").val();
		var profession = $("#profession").val();
		var reason = $("#reason").val();
		if (!address) {
			layer.msg("请选择收货地址!");
			return false;
		}
		if (!name) {
			layer.msg("姓名不能为空!");
			return false;
		}
		if (!profession) {
			layer.msg("职业不能为空!");
			return false;
		}
		if (!reason) {
			layer.msg("申请理由不能为空!");
			return false;
		}
		//请求接口


	});

	/*===默认地址===*/
	$(".switchDe").click(function() {
		if ($(this).hasClass("active")) {
			$(this).removeClass("active");
			$("#isMoren").val("0");
		} else {
			$(".switchDe").removeClass("active");
			$(this).addClass("active");
			$("#isMoren").val("1");
		}
	});
	/*===地区选择===*/
	if ($('#distpicker').length > 0) {
		$('#distpicker').distpicker({
			province: '四川省',
			city: '成都市',
			district: '锦江区'
		});
	}
	/*===收货地址添加/编辑表单提交===*/
	$("#addressSub").click(function() {
		var name = $("#name").val();
		var phone = $("#phone").val();
		var province = $("#distpicker .province").val();
		var city = $("#distpicker .city").val();
		var area = $("#distpicker .area").val();
		var address = $("#address").val();
		var defalt = $("#isMoren").val();
		if (!name) {
			layer.msg("收货人不能为空!");
			return false;
		}
		if (!phone) {
			layer.msg("联系电话不能为空!");
			return false;
		}
		var reg = /(1[3-9]\d{9}$)/;
		if (!reg.test(phone)) {
			layer.msg("手机号格式不正确!");
			return false;
		}
		if (!province || !city || !area) {
			layer.msg("省市区不能为空!");
			return false;
		}
		if (!address) {
			layer.msg("详细地址不能为空!");
			return false;
		}
		//请求接口


	});
	/*===头像修改===*/
	/*===个人资料修改--头像上传===*/
	var inputFile = document.getElementById('avatarFile');
	if(inputFile) {
		inputFile.addEventListener('click', function() {
			this.value = null;
		}, false);
		inputFile.addEventListener('change', readData, false);
	}
	//canvas压缩图片
	function readData(evt) {
		evt.stopPropagation();
		evt.preventDefault();
		var file = evt.dataTransfer !== undefined ? evt.dataTransfer.files[0] : evt.target.files[0];
		if(!file.type.match(/image.*/)) {
			return;
		}
		var reader = new FileReader();
		reader.onload = (function() {
			return function(e) {
				var img = new Image();
				img.src = e.target.result;
				img.onload = (function() {
					var canvas = document.createElement('canvas');
					canvas.width = 150;
					canvas.height = 150;
					var ctx = canvas.getContext("2d");
					ctx.clearRect(0, 0, canvas.width, canvas.height);
					ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
					canvas.toDataURL("image/jpeg");
					UploadImage(canvas.toDataURL("image/jpeg"));
				});
			}
		})(file);
	
		reader.readAsDataURL(file);
	
	}
	//把头像的base64位码传给后台
	function UploadImage(base64) {
		var b64 = base64.split(",")[1];
		//	console.log(b64);
		var load = layer.load(2, {
			shade: [0.1, '#fff']
		});
		$.ajax({
			url: '',
			type: "post",
			data: {
				"photo": b64,
			},
			dataType: 'json',
			success: function(data) {
				if(data.code == '1') {
					$("#txPic").src(data.data.src)
				} else {
					layer.close(load);
					console.log(data.res);
				}
			},
			error: function() {
				layer.close(load);
				layer.msg("图片上传超时!");
			}
		})
	}
	/*===个人信息修改表单提交===*/
	$("#infoSub").click(function() {
		var name = $("#name").val();
		var sex = $("#sex").val();
		var profession = $("#profession").val();
		var age = $("#age").val();	
		if (!name) {
			layer.msg("姓名不能为空!");
			return false;
		}
		if (!profession) {
			layer.msg("职业不能为空!");
			return false;
		}
		//请求接口
	
	
	});
	/*===绑定手机号--发送验证码===*/
	var countdown2 = 60;
	$(".phoneForm #yzmBtn").click(function() {
		if($(this).hasClass("disabled")) {
			return false;
		}
		if(!$("#phoneNum").val()) {
			layer.msg("手机号不能为空!");
			return false;
		}
		var reg = /(1[3-9]\d{9}$)/;
		if(!reg.test($("#phoneNum").val())) {
			layer.msg("手机号格式不正确!");
			return false;
		}
		var obj = $("#yzmBtn");
		settime(obj, countdown2);
	});
	/*===绑定手机号--表单验证===*/
	$(".phoneForm .formSub").click(function() {
		var phoneNum = $("#phoneNum").val();
		var yzm = $("#yzm").val();
		if(!$("#phoneNum").val()) {
			layer.msg("手机号不能为空!");
			return false;
		}
		var reg = /(1[3-9]\d{9}$)/;
		if(!reg.test($("#phoneNum").val())) {
			layer.msg("手机号格式不正确!");
			return false;
		}
		if(!$("#yzm").val()) {
			layer.msg("验证码不能为空!");
			return false;
		}
		$.ajax({
			url: '',
			type: "post",
			data: {
				"phoneNum": phoneNum,
				"yzm": yzm
			},
			dataType: 'json',
			success: function(data) {
				if(data.code == '1') {
	
				} else {
	
				}
			},
			error: function() {
				layer.msg("网络连接错误!");
			}
		})
	});
	/*===弹窗关闭打开===*/
	$(".reportBtn").click(function(){
		var href = $(this).attr("data-href");
		$(".TC .btn").attr("href",href);
		$(".TC").stop().fadeIn();
	});
	$("#closeTC").click(function(){
		$(".TC .btn").attr("href",'');
		$(".TC").stop().fadeOut();
	});
	$(".TC .btn").click(function(){
		$(".TC").stop().fadeOut();
	});
	/*===确认收货===*/
	$(".shouhuoBtn").click(function(){
		layer.confirm('确认收货？', {
		  btn: ['确认','取消'] //按钮
		}, function(){
		  console.log("确认");
		  layer.closeAll('dialog');
		}, function(){
			layer.closeAll('dialog');
		});
	});
	/*===复制淘口令===*/
	$("#copy").click(function() {
	  copyText($("#copyText").text());
	});
	/*===倒计时===*/
	var endtime,nowtime,lefttime,d,h,m,s;
	var sh;
	$.fn.countDown = function(_boolean,_this){
	    var sh = [];
	    // var _this = $(this);
	    _this.each(function(index, el){
	
	    var thisObj = $(this);
	    sh[index]=setInterval(function(){
	        var times = thisObj.data("times");//获得timeBox的data值，即结束时间
	        endtime = new Date(times);//把data值转换成时间
	        nowtime = new Date();//获得当前时间
	        lefttime=parseInt((endtime.getTime()-nowtime.getTime())/1000); //结束时间-当前时间得到毫秒数，再除以1000得到两个时间相差的秒数
	        if(_boolean){
	            d=parseInt(lefttime/3600/24);
	            h=parseInt((lefttime/3600)%24);
	        }else{
	            d=parseInt(lefttime/3600/24)*24;
	            h=parseInt((lefttime/3600)%24)+d;
	        }
	
	        m=parseInt((lefttime/60)%60);
	        s=parseInt(lefttime%60);
	        if(endtime.getTime() <= nowtime.getTime()){
	            d = h = m = s = "0";
	            clearInterval(sh[index]);
	        }
	        // 三目运算符
	        d = d < 10 ? "0"+ d : d;
	        h = h < 10 ? "0"+ h : h;
	        m = m < 10 ? "0"+ m : m;
	        s = s < 10 ? "0"+ s : s;
	
	        if(_boolean){
	            thisObj.find(".date").text(d);
	        }
	
	        thisObj.find(".hour").text(h);
	        thisObj.find(".minutes").text(m);
	        thisObj.find(".seconds").text(s);
	
	        if(lefttime<=0){
	            d = h = m = s = "00";
	            clearInterval(sh[index]);
	        }
	    },1000);
	    });
	}
	$(".cutDown").countDown(true,$(".cutDown"));
});
/*===图片懒加载===*/
function start() {
	$('img').not('[data-isLoaded]').each(function() {
		var $node = $(this)
		if (isShow($node)) {
			loadImg($node)
		}
	})
}

function isShow($node) {
	return $node.offset().top <= $(window).height() + $(window).scrollTop();
}

function loadImg($img) {
	$img.attr('src', $img.attr('data-src'));
	$img.attr('data-isLoaded', 1);
}
/*===tab切换===*/
function tabChange(tab, con, ac) {
	$(tab).click(function() {
		var i = $(this).index();
		$(this).addClass(ac).siblings().removeClass(ac);
		$(con).eq(i).addClass(ac).siblings().removeClass(ac);
	});
}
//去除空格
function Trim(str) {
	var str2;
	if(str == null) {
		str = "";
	} else {
		str2 = str.toString().replace(/(^\s*)|(\s*$)/g, "");
	}
	return str2;
}
//发送验证码倒计时
function settime(obj, num) {
	var countdown = num;
	if(countdown == 0) {
		obj.removeClass('disabled');
		obj.text("获取验证码");
		countdown = 60;
		return;
	} else {
		obj.addClass('disabled');
		obj.text("重新发送(" + countdown + ")");
		countdown--;
	}
	setTimeout(function() {
		settime(obj, countdown)
	}, 1000)
}
// 复制文本内容到剪切板
function copyText(obj) {
  if (!obj) {
    return false;
  }
  var text;
  if (typeof(obj) == 'object') {
    if (obj.nodeType) { // DOM node
      obj = $(obj); // to jQuery object
    }
    try {
      text = obj.text();
      if (!text) { // Maybe <textarea />
        text = obj.val();
      }
    } catch (err) { // as JSON
      text = JSON.stringify(obj);
    }
  } else {
    text = obj;
  }
  //var $temp = $('<input>'); // Line feed is not supported
  var $temp = $('<textarea>');
  $('body').append($temp);
  $temp.val(text).select();
  var res = document.execCommand('copy');
  $temp.remove();
  layer.msg("复制成功!");
  return res;
}